余烬缀记

React 使用函数式组件时出现的问题

edited on:

wallhaven-zmjd7o.jpg

# React 使用函数式组件时出现的问题

# 两次渲染问题

前天在写 React 某个 Demo 代码时发现 React 组件渲染了两次,开始以为是 state 原因,因为函数式组件不使用useState钩子只渲染了一次,但是我思考不明白为什么 React 类组件和使用了useState钩子,开始猜测为因为state原因,

而后在 StackOverflow 上面提问后经热心网友的告知才知道答案,是因为我使用了 React 严格模式,即使用React.StrictMode组件

React StrictMode 文档https://reactjs.org/docs/strict-mode.html

文档上面给出了使用React.StrictMode的副作用

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:

  • Class component constructor method
  • The render method
  • setState updater functions (the first argument)
  • The static getDerivedStateFromProps lifecycle
  • The shouldComponentUpdate method

这次最大的问题还是出在大意上,在找问题时忽略了index.js,因为是使用create-react-app创建了,App.jsindex.js都包含了StrictMode

# React 函数组件在定时器获取 State 问题

<iframe src="https://codesandbox.io/embed/react-function-component-gets-state-in-timer-vyv6g?autoresize=1&fontsize=14&hidenavigation=1&initialpath=%2Freact-shiyong-hanshu-shi-zujian-he-liangci-xuanran-wenti&module=%2Fsrc%2Fcomponents%2Fcounter.tsx&theme=light&view=preview" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="React function component gets state in timer" allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"

在上面点开控制台后连续点击三次Click me可以看到输出了

0
0
1

这是因为变量引用和异步的问题,在函数式很容易遇到因为变量引用而导致的不刷新,最常见的就是当使用useEffect这些需要填写依赖的需要将依赖正确的填写,否者就会出现因为变量引用导致值无变化进而出现问题